# -*- coding: utf-8 -*-

'''
CopyRight(c)2011-2012 Panguso.com. Allrights reserved
File Name: question_classifier.py
File Contents Outline: 
File Created Data: 2013-5-16
File Author: Mao Fan (maofan@panguso.com)
'''
import re, sys
from django.conf import settings
from financial_daily.utils import WordSegUtils

class NewsClassifiers:
  '''
  将新闻分类
  '''

  def __init__(self):
    '''
    config_file = './config/question_classifier.ini'
    self.config = ConfigObj(config_file)

    self.category_re_list = list()
    for cat_name, cat_re_str in self.config['classification'].iteritems():
      cat_re = re.compile(cat_re_str.decode('utf8'))
      self.category_re_list.append((cat_name, cat_re))
    '''
    self.category_re_list = list()
    for cat_name, cat_re_str in settings.QUESTION_CLASSIFY_PARAMS.iteritems():
      cat_re = re.compile(cat_re_str.decode('utf8'))
      self.category_re_list.append((cat_name, cat_re))

  def __get_tags(self, terms):
    tags = set()
    for term in terms:
      for cat_name, cat_re in self.category_re_list:
        if cat_re.search(term) != None:
          tags.add(cat_name)
    return tags

  def __check_big_events(self, tags_set):
    sub_cat = None
    if 'Reorg' in tags_set:
      sub_cat = u'并购重组'
    elif 'Financing' in tags_set:
      sub_cat = u'再融资'
    elif 'Lawsuit' in tags_set:
      sub_cat = u'诉讼'
    elif 'Projects' in tags_set:
      sub_cat = u'项目进展'
    elif 'Shares' in tags_set:
      sub_cat = u'股份变动'
    elif 'Options' in tags_set:
      sub_cat = u'股权激励'
    
    if sub_cat != None:
      return u'重大事项', sub_cat
    else:
      return None, None
  
  def __check_financial_index(self, tags_set):
    sub_cat = None
    if 'Dividend' in tags_set:
      sub_cat = u'分红'
    elif 'Performance' in tags_set:
      sub_cat = u'业绩'
    elif 'KPI' in tags_set:
      sub_cat = u'财务指标'

    if sub_cat != None:
      return u'财务数据', sub_cat
    else:
      return None, None

  def __check_management_info(self, tags_set):
    sub_cat = None
    if 'ManagementChange' in tags_set:
      sub_cat = u'高管变动'
    elif 'ManagementWage' in tags_set:
      sub_cat = u'高管薪酬'
    elif 'ManagementHolding' in tags_set:
      sub_cat = u'高管持股'

    if sub_cat != None:
      return u'高管信息', sub_cat
    else:
      return None, None

  def classify(self, news_str):
    seg_tokens = WordSegUtils.word_segment_phrase(news_str)
    token_list = [token['lexemeText'] for token in seg_tokens]
    tags = self.__get_tags(token_list)
    
    category_checkers = [self.__check_big_events, self.__check_financial_index, self.__check_management_info]
    for checker in category_checkers:
      main_cat, sub_cat = checker(tags)
      if main_cat != None:
        return main_cat, sub_cat
    return u'其他', u'其他'


    

